package com.quectel.core.module.partyeducation.service.impl;


import com.google.common.base.Preconditions;
import com.quectel.constant.core.partyeducation.PartyEducationLibraryConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.util.aspect.lock.annotation.Lock;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.partybuilding.dto.PartyOrganizationDto;
import com.quectel.core.module.partybuilding.service.PartyOrganizationService;
import com.quectel.core.module.partyeducation.dao.PartyEducationLibraryDao;
import com.quectel.core.module.partyeducation.dto.PartyEducationLibraryDto;
import com.quectel.core.module.partyeducation.dto.PartyEducationLibraryUserDto;
import com.quectel.core.module.partyeducation.entity.PartyEducationLibraryEntity;
import com.quectel.core.module.partyeducation.service.PartyEducationLibraryService;
import com.quectel.core.module.partyeducation.service.PartyEducationLibraryUserService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
/**
 *
 * @author ryan
 * @email ryan.ran@quectel.com
 * @date 2023/06/13 17:18
 */
@DubboService
public class PartyEducationLibraryServiceImpl implements PartyEducationLibraryService{

    private static final Logger LOGGER = LoggerFactory.getLogger(PartyEducationLibraryServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> PARTY_EDUCATION_LIBRARY_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "PARTY_EDUCATION_LIBRARY_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<PartyEducationLibraryDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(PARTY_EDUCATION_LIBRARY_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    /**
     * 资源访问计数锁
     */
    public static final String RESOURCE_CHECK_LOCK =
            RedisCacheConstants.PROJECT_NAME + "RESOURCE_CHECK:";

    @Autowired
    private PartyEducationLibraryDao partyEducationLibraryDao;
    @Autowired
    private PartyOrganizationService partyOrganizationService;
    @Autowired
    private PartyEducationLibraryUserService partyEducationLibraryUserService;


    @Override
    @Lock(
            lockExpresses = {
                    RESOURCE_CHECK_LOCK + "#{#partyEducationLibraryUserDto.libraryId}"
            }
    )
    @Transactional
    public void check(PartyEducationLibraryUserDto partyEducationLibraryUserDto) {
        PartyEducationLibraryDto partyEducationLibraryDto = selectById(partyEducationLibraryUserDto.getLibraryId());
        Preconditions.checkNotNull(partyEducationLibraryDto);

        PartyEducationLibraryDto newlyDto = new PartyEducationLibraryDto();
        newlyDto.setId(partyEducationLibraryDto.getId());
        if (PartyEducationLibraryConstants.CheckTypeEnum.BROWSE.getCheckType().equals(partyEducationLibraryUserDto.getCheckType())) {
            newlyDto.setBrowseCount(Objects.nonNull(partyEducationLibraryDto.getBrowseCount()) ? partyEducationLibraryDto.getBrowseCount() + 1 : 0);
        } else if (PartyEducationLibraryConstants.CheckTypeEnum.DOWNLOAD.getCheckType().equals(partyEducationLibraryUserDto.getCheckType())) {
            newlyDto.setDownloadCount(Objects.nonNull(partyEducationLibraryDto.getDownloadCount()) ? partyEducationLibraryDto.getDownloadCount() + 1 : 0);
        }
        updateById(newlyDto);

        partyEducationLibraryUserService.save(partyEducationLibraryUserDto);
    }

    @Override
    public PartyEducationLibraryDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                PARTY_EDUCATION_LIBRARY_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public PartyEducationLibraryDto selectById(Long id){
            PartyEducationLibraryEntity entity = partyEducationLibraryDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity,PartyEducationLibraryDto.class));
    }

    @Override
    public List<PartyEducationLibraryDto> queryList(Map<String,Object> params){
        List<PartyEducationLibraryEntity> list = partyEducationLibraryDao.queryList(params);
        List<PartyEducationLibraryDto> result =  CopyUtils.copyList(list,PartyEducationLibraryDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    @Override
    public List<PartyEducationLibraryDto> queryListWithoutPadding(Map<String,Object> params){
        List<PartyEducationLibraryEntity> list = partyEducationLibraryDao.queryList(params);
        return CopyUtils.copyList(list,PartyEducationLibraryDto.class);
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private PartyEducationLibraryDto paddingField(PartyEducationLibraryDto dto){
        if (dto != null){
            PartyOrganizationDto partyOrganizationDto = partyOrganizationService.selectById(dto.getPartyId());
            dto.setParty(partyOrganizationDto);
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params){
        return partyEducationLibraryDao.queryTotal(params);
    }

    @Override
    public Long save(PartyEducationLibraryDto dto){
        PartyEducationLibraryEntity entity = CopyUtils.copyObj(dto,PartyEducationLibraryEntity.class);
        entity.setId(Snowflake.nextId());
        partyEducationLibraryDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(PartyEducationLibraryDto dto){
        PartyEducationLibraryEntity entity = CopyUtils.copyObj(dto,PartyEducationLibraryEntity.class);

        partyEducationLibraryDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(PartyEducationLibraryDto dto) {
       PartyEducationLibraryEntity entity = CopyUtils.copyObj(dto,PartyEducationLibraryEntity.class);

       MyBatisPlusUtils.updateAllColumnById(entity, partyEducationLibraryDao);

       CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id){

        CLEAR_CACHE_FUNC.accept(selectById(id));

        partyEducationLibraryDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids){
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
